package profile

import (
	"context"
	"time"

	"usercenter/internal/biz"
	"usercenter/internal/middleware"
	"usercenter/internal/svc"
	"usercenter/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetMyInfoLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetMyInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetMyInfoLogic {
	return &GetMyInfoLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetMyInfoLogic) GetMyInfo() (resp *types.UserInfoResponse, err error) {
	// 1. 从上下文中获取用户ID
	// userId, ok := l.ctx.Value("userId").(int)
	userId, ok := l.ctx.Value(middleware.UserIdKey).(int)
	if !ok || userId == 0 {
		return nil, &biz.BizError{
			Code:    401,
			Message: "未授权访问",
		}
	}

	// 2. 查询用户信息
	user, err := l.svcCtx.UserModel.FindById(userId)
	if err != nil {
		l.Logger.Errorf("查询用户信息失败: %v", err)
		return nil, &biz.BizError{
			Code:    500,
			Message: "查询用户信息失败",
		}
	}

	// 3. 构建响应
	return &types.UserInfoResponse{
		Code:    200,
		Message: "success",
		Data: types.UserInfo{
			Id:        int(user.ID),
			Name:      user.Name,
			Email:     user.Email,
			Avatar:    user.Avatar, // 假设User模型中有Avatar字段
			CreatedAt: user.CreatedAt.Format(time.RFC3339),
			UpdatedAt: user.UpdatedAt.Format(time.RFC3339),
		},
	}, nil
}
